package com.base.component.ai.platform.minimax;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.core.json.JsonArray;
import com.gitee.magic.core.json.JsonObject;
import com.gitee.magic.core.utils.codec.Base64;
import com.gitee.magic.framework.base.rest.HttpMultipartForm;
import com.gitee.magic.framework.base.rest.HttpMultipartForm.MultipartForm;
import com.gitee.magic.framework.base.rest.HttpRequest;
import com.gitee.magic.framework.base.rest.HttpWrapper;

@ConditionalOnProperty(
		prefix = "minimax",
		value = {"apiKey","groupId"})
@Component
public class MinimaxVoiceHandler {

	@Value("${minimax.url:https://api.minimax.chat}")
	private String url;
	@Value("${minimax.apiKey}")
	private String apiKey;
	@Value("${minimax.groupId}")
	private String groupId;

	/**
	 * https://platform.minimaxi.com/document/T2A%20Pro?key=667bde173be2027f69b71d66
	 * @param text
	 */
	public String t2aPro(String text,String voiceId) {
		JsonObject req = new JsonObject();
		req.put("text", text);
		req.put("voice_id", voiceId);
//		req.put("voice_id", "tengzhan_duihua_speech02_516");
		req.put("model", "speech-02");
		req.put("speed",1);
		req.put("vol", 8.0);
		req.put("pitch",0);
		req.put("audio_sample_rate", 16000);
		req.put("bitrate", 32000);
		
		HttpRequest request = new HttpRequest(url+"/v1/t2a_pro");
		request.setHeader(HttpWrapper.AUTHORIZATION, "Bearer " + apiKey);
		request.setHeader(HttpWrapper.CONTENTTYPE, HttpWrapper.CONTENTTYPE_JSON);
		request.setUrlParam("GroupId", groupId);
		request.setBodyContent(req.toString());
		HttpWrapper wrapper = new HttpWrapper();
		String content = wrapper.start(request);
		System.out.println(content);
		JsonObject js = new JsonObject(content);
		System.out.println(js.getString("audio_file"));
		System.out.println(js.getString("subtitle_file"));
		return js.getString("audio_file");
	}

	public byte[] textToSpeech(String content,String voiceId) {
		JsonObject req = new JsonObject();
		req.put("text", content);
		req.put("voice_id", voiceId);

		HttpRequest request = new HttpRequest(url+"/v1/text_to_speech");
		request.setHeader(HttpWrapper.AUTHORIZATION, "Bearer " + apiKey);
		request.setHeader(HttpWrapper.CONTENTTYPE, HttpWrapper.CONTENTTYPE_JSON);
		request.setUrlParam("GroupId", groupId);
		request.setBodyContent(req.toString());
		HttpWrapper wrapper = new HttpWrapper();
		HttpURLConnection connection = wrapper.requestConnect(request);
		byte[] bytes = wrapper.startToBytes(request, connection);
		System.out.println(Base64.encode(bytes));
		return bytes;
	}
	
	public String uploadFile(File file) {
		try {
			return uploadFile(file.getName(),new FileInputStream(file));
		} catch (FileNotFoundException e) {
			throw new ApplicationException(e);
		}
	}
	
	public String uploadFile(String name,InputStream is) {
		HttpRequest request = new HttpRequest(url+"/v1/files/upload");
		request.setHeader(HttpWrapper.CONTENTTYPE, "multipart/form-data");
		request.setHeader(HttpWrapper.AUTHORIZATION, "Bearer " + apiKey);
		request.setHeader("authority", "api.minimax.chat");
		request.setUrlParam("GroupId", groupId);
		HttpWrapper wrapper = new HttpWrapper();
		HttpURLConnection connection = wrapper.requestConnect(request);
		Map<String,String> formParams=new HashMap<>();
		formParams.put("purpose", "voice_clone");
		Map<String,MultipartForm> multipartParams=new HashMap<>();
		multipartParams.put(name, new MultipartForm() {

			@Override
			public InputStream getInputStream() {
				return is;
			}
			
		});
		HttpMultipartForm.multipartFormData(connection, formParams, multipartParams);
		String content=wrapper.start(request,connection);
		System.out.println(content);
		JsonObject result=new JsonObject(content);
		return result.getJsonObject("file").getString("file_id");
	}
	
	/**
	 * 声音克隆
	 * @see https://platform.minimaxi.com/document/Voice%20Cloning?key=66719032a427f0c8a570165b
	 * @param text
	 */
	public JsonObject voiceClone(String fileId,String voiceId) {
		JsonObject req = new JsonObject();
		req.put("file_id", fileId);
		req.put("voice_id",voiceId);
//		req.put("voice_id","MiniMadsadsdx00225");
//		req.put("text_validation","一闪一闪亮晶晶，满天都是小星星。挂在天空放光明，好像许多小眼睛。");
//		req.put("accuracy",0.8);
		HttpRequest request = new HttpRequest(url+"/v1/voice_clone");
		request.setHeader(HttpWrapper.AUTHORIZATION, "Bearer " + apiKey);
		request.setHeader(HttpWrapper.CONTENTTYPE, HttpWrapper.CONTENTTYPE_JSON);
		request.setUrlParam("GroupId", groupId);
		request.setBodyContent(req.toString());
		HttpWrapper wrapper = new HttpWrapper();
		String content = wrapper.start(request);
		System.out.println(content);
		return new JsonObject(content);
	}

	/**
	 * https://platform.minimaxi.com/document/VoiceGeneration?key=669f5af198ff2c57eeb9a0f0
	 * Voice Generation（文生音色）
	 */
	public String text2Voice(String text,String gender,String ageName,List<String> descs) {
		JsonObject req = new JsonObject();
		req.put("text", text);
		req.put("gender", gender);
		req.put("age", ageName);
		JsonArray a=new JsonArray();
		for(String desc:descs) {
			a.put(desc);
		}
//		a.put("Kind and amiable");
//		a.put("Kind hearted");
//		a.put("Calm tone");
		req.put("voice_desc", a);
		HttpRequest request = new HttpRequest(url+"/v1/text2voice");
		request.setHeader(HttpWrapper.AUTHORIZATION, "Bearer " + apiKey);
		request.setHeader(HttpWrapper.CONTENTTYPE, HttpWrapper.CONTENTTYPE_JSON);
		request.setUrlParam("GroupId", groupId);
		request.setBodyContent(req.toString());
		HttpWrapper wrapper = new HttpWrapper();
		String content = wrapper.start(request);
		System.out.println(content);
		JsonObject result=new JsonObject(content);
		return result.getString("voice_id");
	}

	public static void main(String[] args) {

		MinimaxVoiceHandler tts = new MinimaxVoiceHandler();
		tts.url = "https://api.minimax.chat";
		tts.apiKey = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJHcm91cE5hbWUiOiLmna3lt57otoXlnZfnp5HmioDmnInpmZDlhazlj7giLCJVc2VyTmFtZSI6IueOi-mYsyIsIkFjY291bnQiOiIiLCJTdWJqZWN0SUQiOiIxNzQyNTUzOTE4MjMzMTIwNzc4IiwiUGhvbmUiOiIxOTAxMjg5NTk3MiIsIkdyb3VwSUQiOiIxNzQyNTUzOTE4MjI0NzMyMTcwIiwiUGFnZU5hbWUiOiIiLCJNYWlsIjoiIiwiQ3JlYXRlVGltZSI6IjIwMjQtMDEtMDQgMTE6NDk6MzMiLCJpc3MiOiJtaW5pbWF4In0.h39o7e0obmqk-IzjwS3veFkp5r0goztPgLYOLkq_IXOrsltWIsK1kQlQj0vowy-qNTW42mROexX7Ah2AdjRkDPnf85WBAbHZkw5t2pIMeizjkY6_ZJVGhYFMQTVt0JypGjHBCz32v4sQBlOSK_9tvK2JvCfQd5bZtxHvl6fUTAbBMg4sDLCjVIAJcF6yLZeJxCkV7dDAQeJGvGogJt98lyE0V4DJFNU7QZJZxtsatUMkVmzx-FW-wVggTazD6Aa-JtXIeI9COT07jGe5cfTen7R5QDox8zXrwJjvS2cQonerjdCNEnV9_ivG9AQKdH61MIcID5DaRSGSiLI4jpdZ6Q";
		tts.groupId = "1742553918224732170";

//		tts.filesUpload(new File("C:\\Users\\zywei\\Downloads\\audio_tts-mp3-20240928114653-XNHrKcAl.mp3"));
//		tts.voiceClone(188165719117987L);
//		tts.t2aPro("我今天无敌了");
//		tts.text2Voice("真正的危险不是计算机开始像人一样思考，而是人开始像计算机一样思考");
//		 tts.handle("我今天无敌了");
	}

}
